import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_app/bean/list_sign_entity.dart';
import 'package:flutter_app/r.dart';
import 'package:flutter_app/ui/apply/apply_detail/apply_detail_view.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/ui/apply/ApplyListModel.dart';
import 'package:flutter_app/widget/empty_view.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';


/**
 * @Description: 首页 tab 详情
 * @Author: 下雨了
 * @CreateDate: 2021-10-15 16:57
 * @UpdateUser: 更新者
 * @UpdateDate:  2021-10-15 16:57
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
class ApplyListPage extends StatefulWidget {
  // 0全部 1明查暗访 2窗口值班 3其他活动
  final String page;
  const ApplyListPage({Key? key, required this.page}) : super(key: key);

  @override
  _ApplyListPageState createState() => _ApplyListPageState();
}

class _ApplyListPageState extends State<ApplyListPage> with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  late ApplyListModel _applyListModel;
  ListSignEntity? listSignEntity;
  int currentPage = 1; // 当前页面

  // 订阅事件 HomeEvent
  late StreamSubscription<ApplyEvent> _homeEvent;


  /// 刷新
  void _onRefresh() async {
    currentPage = 1;
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    _applyListModel.postListSign(currentPage, widget.page).then((value) {
      _refreshController.refreshCompleted();
      _refreshController.resetNoData();
    });
  }

  /// 加载
  void _onLoading() async {
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果完成使用loadFailed，如果没有数据返回，使用LoadNodata()
    if (mounted) setState(() {});
    int? totalPages = _applyListModel.listSignEntity!.totalPages;
    if (currentPage < totalPages!) {
      currentPage++;
      _applyListModel.postListSign(currentPage, widget.page).then((value) =>  _refreshController.loadComplete());
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  void initState() {
    super.initState();
    _applyListModel = context.read<ApplyListModel>();
    _applyListModel.postListSign(currentPage, widget.page);

    /// 订阅事件 HomeEvent 处理
    _homeEvent = bus.listen((event) {
      _applyListModel.upSignData(event.collectId, event.status, event.totalSign);
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 取消订阅
    _homeEvent.cancel();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    listSignEntity = context.watch<ApplyListModel>().listSignEntity;
    return SmartRefresher(
      controller: _refreshController,
      //  允许下拉刷新
      enablePullDown: true,
      // 允许上拉加载
      enablePullUp: true,
      // 刷新
      onRefresh: _onRefresh,
      // 加载
      onLoading: _onLoading,
      header: WaterDropHeader(complete: Text('刷新完成', style: TextStyle(color: MyColors.FF333333))),
      footer: ClassicFooter(loadingText: '加载中...', idleText: '上拉加载更多..', noDataText: '没有更多数据了'),
      child: (listSignEntity?.content?.length ?? 0) > 0 ? ListView.builder(
        itemBuilder: (context, index) {
          return _ApplyListItem(listSignEntity!.content![index]);
        }, 
        itemCount: listSignEntity?.content!.length,
        physics: BouncingScrollPhysics(),
      ) : EmptyView(),
    );
  }

  Widget _ApplyListItem(ListSignContent item) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4.r),
        color: Colors.white
      ),
      margin: EdgeInsets.fromLTRB(16.r, 5.r, 16.r, 7.r),
      child: Stack(
        children: [
          Visibility(visible: item.collectStatus! == "3", child: Align(alignment: Alignment.topRight, child: Image.asset(R.assetsImgIcon53, height: 47.5.r))),
          Container(
            padding: EdgeInsets.fromLTRB(16.r, 15.r, 16.r, 19.r),
            child: InkWell(
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("发布时间：" + DateTime.parse(item.createTime!).toString().substring(0, 16), style: TextStyle(color: MyColors.FF777777, fontSize: 12.sp),),
                        Container(
                          margin: EdgeInsets.only(top: 7.5.r, right: 30.r),
                          child: Text(item.taskName!,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyColors.FF333333, fontSize: 15.sp, fontWeight: FontWeight.w600),),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 4.r),
                          child: Row(
                            children: [
                              // Image.asset(item.taskType == "1" ? R.assetsImgIcon5 : R.assetsImgIcon36, width: 35,),
                              Container(
                                padding: EdgeInsets.fromLTRB(5.r, 1.r, 5.r, 1.5.r),
                                decoration: BoxDecoration(
                                    color: MyColors.FFFDE6E5,
                                    borderRadius: BorderRadius.circular(2)
                                ),
                                child: Text(item.taskType == "1" ? "暗访" : item.taskType == "2" ? "值班" : "其他", style: TextStyle(color: MyColors.FFF03F35, fontSize: 12.sp),),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 6.r, right: 6.r),
                                padding: EdgeInsets.fromLTRB(5.r, 1.r, 5.r, 1.5.r),
                                decoration: BoxDecoration(
                                    color: MyColors.FFECF6FE,
                                    borderRadius: BorderRadius.circular(2.r)
                                ),
                                child: Text("已报名"+ item.totalSign! +" 人", style: TextStyle(color: MyColors.FF2763B9, fontSize: 12.sp),),
                              ),
                              Visibility(visible: int.parse(item.limitDay!) >= 0,
                                child: Container(
                                    padding: EdgeInsets.fromLTRB(5.r, 1.r, 5.r, 1.5.r),
                                    decoration: BoxDecoration(
                                        color: MyColors.FFECF6FE,
                                        borderRadius: BorderRadius.circular(2.r)
                                    ),
                                    child: Row(
                                      children: [
                                        Container(margin: EdgeInsets.only(top: 2.r, right: 3.5.r), child: Image.asset(R.assetsImgIcon54, height: 11.5.r,)),
                                        Text(int.parse(item.limitDay!) == 0 ? "今日到期" : "倒计时"+ item.limitDay! + "天", style: TextStyle(color: MyColors.FF2763B9, fontSize: 12.sp),),
                                      ],
                                    )
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  Center(
                    child: TextButton(
                      child: Text(item.isLimit == "1" ? "过期" : item.status == "0" ? "报名" : "已报", style: TextStyle(color: Colors.white, fontSize: 15.sp),),
                      style: ButtonStyle(
                        padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                        backgroundColor: MaterialStateProperty.all<Color>(_getButtonColors(item)),
                        minimumSize: MaterialStateProperty.all(Size(57.r, 30.r)),
                      ),
                      onPressed: () {
                        Get.to(() => ApplyDetailPage(title: "报名详情",), arguments: item.collectId);
                      },
                    ),
                  )
                ],
              ),
              onTap: () {
                Get.to(() => ApplyDetailPage(title: "报名详情",), arguments: item.collectId)?.then((value) {
                  // 判断是否刷新
                  if (value == "refresh") {
                    // 刷新操作
                    _onRefresh();
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  // 获取button 颜色
  Color _getButtonColors(ListSignContent item) {
    if (item.collectStatus == "3") {
      return MyColors.FFFDB7A7;
    } else {
      if (item.isLimit == "0" && item.status == "0") {
        return MyColors.FFF03F35;
      } else {
        return MyColors.FFFDB7A7;
      }
    }
  }

  @override
  bool get wantKeepAlive => true;
}
